<template>
  <div class="count_input_main">
    <a-input
      :defaultValue="defaultValue"
      :value="inputValue"
      :style="{ width: width + 'px' }"
      @change="handleInputChange"
      @blur="handleTagInputConfirm"
    >
      <a-icon slot="prefix" type="minus" @click="minusNum()" />
      <a-icon slot="suffix" type="plus" @click="plusNum()" />
    </a-input>
  </div>
</template>

<script>
export default {
  name: 'CountInput',
  props: {
    maxValue: {
      type: Number,
      default: 999
    },
    minValue: {
      type: Number,
      default: 1
    },
    defaultValue: {
      type: Number,
      default: 1
    },
    width: {
      type: Number,
      default: 117
    }
  },
  data() {
    return {
      inputValue: this.defaultValue
    }
  },
  created() {},
  methods: {
    handleInputChange(e) {
      if (!/(^[1-9]\d*$)/.test(e.target.value)) {
        this.inputValue = this.defaultValue
      } else if (parseInt(e.target.value) < parseInt(this.minValue)) {
        this.inputValue = this.minValue
      } else if (parseInt(e.target.value) > parseInt(this.maxValue)) {
        this.inputValue = this.maxValue
      } else {
        this.inputValue = e.target.value
      }
      this.$forceUpdate()
    },
    handleTagInputConfirm() {
      if (!/(^[1-9]\d*$)/.test(this.inputValue)) {
        this.inputValue = this.defaultValue
        this.$forceUpdate()
      }
      this.$emit('handleInputValue', parseInt(this.inputValue))
    },
    minusNum() {
      let inputValue = this.inputValue
      if (!/(^[1-9]\d*$)/.test(inputValue)) {
        inputValue = this.defaultValue
      } else if (parseInt(inputValue) === parseInt(this.minValue)) {
        inputValue = this.minValue
      } else {
        inputValue = inputValue - 1
      }
      this.inputValue = inputValue
      this.$emit('handleInputValue', parseInt(this.inputValue))
    },
    plusNum() {
      let inputValue = this.inputValue
      if (!/(^[1-9]\d*$)/.test(inputValue)) {
        inputValue = this.defaultValue
      } else if (parseInt(inputValue) === parseInt(this.maxValue)) {
        inputValue = this.maxValue
      } else {
        inputValue = parseInt(inputValue) + 1
      }
      this.inputValue = inputValue
      this.$emit('handleInputValue', parseInt(this.inputValue))
    }
  }
}
</script>

<style lang="less" scoped>
.count_input_main {
  border: 1px solid #e1e5ee;
  /deep/.ant-input {
    height: 28px;
    border: none;
    text-align: center;
  }
  /deep/.ant-input-prefix {
    width: 28px;
    height: 28px;
    left: 0;
    background-color: #f6f8fd;
    border-right: 1px solid #e1e5ee;
  }
  /deep/.ant-input-prefix:hover {
    cursor: pointer;
  }
  /deep/.ant-input-suffix {
    width: 28px;
    height: 28px;
    right: 0;
    background-color: #f6f8fd;
    border-left: 1px solid #e1e5ee;
  }
  /deep/.ant-input-suffix:hover {
    cursor: pointer;
  }
  /deep/.anticon {
    width: 100%;
    justify-content: center;
  }
}
</style>
